<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        show-icon
        :closable="false"
        title="注意!只允许为第三级分类设置相关参数"
        type="warning"
      ></el-alert>
      <el-row class="cat_opt">
        <el-col :span="5"><span>选择商品分类：</span></el-col>
        <el-col :span="5"
          ><el-cascader
            v-model="selectedKeys"
            :options="catelist"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="handleChange"
          ></el-cascader
        ></el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            @click="addAttrDialogVisible = true"
            :disabled="isBtnDisabled"
            >添加动态参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand" >
              <template slot-scope="scope">
                <el-tag
                  @close='attrTagClosed(index,scope.row,scope.$index)'
                  closable
                  v-for="(item, index) in scope.row.attr_vals.split(',')"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row,scope.$index)"
                  >+ 新项</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="toShowEditDialog(scope.row,scope.$index)"
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                ></el-button>
                <el-button
                  @click="attrDelete(scope.row)"
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            @click="addAttrDialogVisible = true"
            :disabled="isBtnDisabled"
          >
            添加静态属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column
              label="属性值"
              prop="attr_vals"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row)"
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                ></el-button>
                <el-button
                  @click="attrDelete(scope.row)"
                  icon="el-icon-delete"
                  type="danger"
                  size="mini"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addAttrDialogVisible"
      width="50%"
      @close="addAttrDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item
          label="动态选项"
          prop="attr_vals"
        >
          <el-input v-model="addForm.attr_vals" prop="attr_vals"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 以上为添加参数对话框 -->
    <!-- 以下为修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editAttrDialogVisible"
      width="50%"
      @close="editAttrDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item
          label="动态选项"
          prop="attr_vals"
        >
          <el-input v-model="editForm.attr_vals" prop="attr_vals"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrDialogClose">取 消</el-button>
        <el-button type="primary" @click="editAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catelist: [],
      selectedKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addAttrDialogVisible: false,
      editAttrDialogVisible: false,
      addForm: {
        attr_name: '',
        attr_vals: '',
      },
      editForm: {
        attr_name: '',
        attr_vals: '',
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      tagTemp:'',//tag点击new tag或点击删除tag时临时保存一下attr_vals
      rowIndex:0
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200)
        return this.$message.error('获取列表数据失败')
      this.catelist = res.data
      console.log(this.catelist)
    },
    handleChange() {
      console.log(this.selectedKeys)
      this.getCateAttributes()
    },
    handleTabClick() {
      console.log(this.activeName)
      this.getCateAttributes()
    },
    async getCateAttributes() {
      if(this.selectedKeys.length!==3){
        this.selectedKeys=[]
        this.manyTableData=[]
        this.onlyTableData=[]
        }
      const { data: res } = await this.$http.get(
        'categories/' + this.cateId + '/attributes',
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      res.data.forEach((item) => {
        item.inputVisible = false //这两行是给new tag加新值的时候存状态和值用的
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else {
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    addAttrDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // addAttrDialogVisible = false
    addAttr() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('验证失败')
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
            attr_vals:  this.addForm.attr_vals 
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.getCateAttributes()
        this.addAttrDialogVisible = false
      })
    },
    showEditDialog(item) {
      this.editForm.attr_name = item.attr_name
      this.editForm.attr_id = item.attr_id
      this.editForm.attr_vals = item.attr_vals
      this.editAttrDialogVisible = true
      console.log(this.editForm)
    },
    editAttrDialogClose() { 
      this.$refs.editFormRef.resetFields()
      if(this.activeName==='many'){
        this.manyTableData[this.rowIndex].attr_vals=this.tagTemp
      }
      this.editAttrDialogVisible = false
      
    },
    toShowEditDialog(item,$i){
         this.showEditDialog(item)
         this.tagTemp=item.attr_vals
         this.rowIndex=$i
    },
    editAttr() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('验证失败')
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
            attr_vals:this.editForm.attr_vals
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getCateAttributes()
        this.editAttrDialogVisible = false
      })
    },
    async attrDelete(item) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该属性, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm')
        return this.$message.info('用户已取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${item.attr_id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getCateAttributes()
      this.editAttrDialogVisible = false
    },
    handleInputConfirm(item) {
      //tag中new tag触发
      if (item.inputValue.trim().length !== 0) {
        if (item.attr_vals === '' || item.attr_vals === undefined) {
          item.attr_vals = item.attr_vals + item.inputValue.trim()
        } else {
          item.attr_vals = item.attr_vals + ',' + item.inputValue.trim()
        }
      }
      item.inputValue = ''
      item.inputVisible = false
      this.showEditDialog(item)

    },
    attrTagClosed(index,row,$i){
      this.tagTemp= row.attr_vals
      this.rowIndex=$i
      const arr=row.attr_vals= row.attr_vals.split(',')
      arr.splice(index,1)
      row.attr_vals=arr.join(',')
      this.showEditDialog(row)

    },
    showInput(item,$i) {
      this.tagTemp= item.attr_vals
      this.rowIndex=$i
      item.inputVisible = true
      this.$nextTick((_) => {
        //文本框自动获取焦点 $nextTick:当页面上的元素被重新渲染之后执行回调函数  这个用于  在刚刚被渲染出来的元素上操作，如果没有nextTick，则可能代码在元素渲染出来之前先执行了，就会无效
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedKeys.length > 0) return false
      return true
    },
    cateId() {
      if (this.selectedKeys.length > 0) return this.selectedKeys[2]
    },
    titleText() {
      if (this.activeName === 'many') return '动态参数'
      return '静态属性'
    },
  },
}
</script>

<style scopted>
.cat_opt {
  margin: 15px;
}
.input-new-tag {
  width: 150px !important;
}
</style>